package com.example.computer_exam_training_sys.mapper;

import com.example.computer_exam_training_sys.entity.SysLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import java.util.List;

@Mapper
public interface SysLogMapper {
    // SysLogMapper.java
    @Select("<script>" +
            "SELECT l.log_id AS logID, l.user_id AS userID, l.log_content AS logContent, " +
            "l.ip_address AS ipAddress, l.os, l.ie, l.create_time AS createTime, " +
            "u.real_name AS userName, u.is_admin AS isAdmin " + // 新增isAdmin字段
            "FROM sys_log l " +
            "LEFT JOIN users u ON l.user_id = u.user_id " +
            "WHERE 1=1 " +
            "<if test='userName != null and userName != \"\"'> AND u.real_name LIKE CONCAT('%', #{userName}, '%') </if>" +
            "<if test='startDate != null and startDate != \"\"'> AND DATE(l.create_time) = #{startDate} </if>" +
            "ORDER BY l.create_time DESC " +
            "LIMIT #{offset}, #{size}" +
            "</script>")
    List<SysLog> searchLogsPaged(
            @Param("userName") String userName,
            @Param("startDate") String startDate,
            @Param("offset") int offset,
            @Param("size") int size
    );

    @Select("<script>" +
            "SELECT COUNT(*) FROM sys_log l " +
            "LEFT JOIN users u ON l.user_id = u.user_id " +
            "WHERE 1=1 " +
            "<if test='userName != null and userName != \"\"'> AND u.real_name LIKE CONCAT('%', #{userName}, '%') </if>" +
            "<if test='startDate != null and startDate != \"\"'> AND DATE(l.create_time) = #{startDate} </if>" +
            "</script>")
    int countLogs(
            @Param("userName") String userName,
            @Param("startDate") String startDate
    );

    // ✅ 新增：插入登录日志的方法
    @Insert("INSERT INTO sys_log (user_id, log_content, ip_address, os, ie) " +
            "VALUES (#{userID}, #{logContent}, #{ipAddress}, #{os}, #{ie})")
    int insertLog(SysLog log);
}